
const config = require('wy-Config');
const querystring = require("querystring");
var Http = {
    setOptions(option){
        option.token && (this.token = option.token);
        option._id && (this._id = option._id);
    },
    post: function (router, params, cb) {
        var sendstr = JSON.stringify(params);
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("POST", config.httpRootUrl + router, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 300)) {
                try {
                    var data = JSON.parse(xhr.response);
                    if (!!cb && data.code === 200) {
                        cb(data.data);
                    } else {
                        global.EJMgr.showToast(data.msg)
                    }
                } catch (e) {
                    cc.error("err:" + e);
                }
            }
        };
        xhr.send(sendstr);
    },

    get: function (objname,router, params, cb, reconnect) {
        router&& (params.router = router);
        this._id&& (params._id = this._id);
        this.token&& (params.token = this.token);

        let url = `${config.httpRootUrl}${objname}?${querystring.stringify(params)}`;
        // cc.log('httpurl:',url);
        const xhr = cc.loader.getXMLHttpRequest();
        xhr.route = router
        xhr.open("GET", url, true);
        var timeout = setTimeout(function(){
            xhr.abort();
        },30000)
        xhr.onreadystatechange = () => {
            if(xhr.readyState === 4){
                clearTimeout(timeout);
                if(xhr.status >= 200 && xhr.status < 300){
                    cc.log('resp:'+xhr.response)
                    var data = null;
                    try {
                        data = JSON.parse(xhr.response);
                    } catch (e) {
                        cb(e,null);
                        cc.error("err:" + e);
                        return;
                    }
                    if (!!cb && data.code === 200) {
                        cb(null,data.data);
                    } else {
                        cb(data.code,data.data);
                        
                        cc.log('登陆失败！'+data);
                        global.EJMgr.showToast(data.msg)
                    }
                } else if(reconnect){
                    setTimeout(function(){
                        Http.get(objname,router, params, cb, reconnect)
                    },1500)
                }
                else {
                    cb(''+xhr.status,null);
                }
            }
        }
        
        xhr.send();
        return xhr;
    }
}

module.exports = Http;